package com.leetcode;

import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

/**
 * 819. 最常见的单词
 * StringBuilder暂存字符串
 *
 * @author fy
 * @date 2022-04-17 11:35
 */
public class Solution819_1 {

    public String mostCommonWord(String paragraph, String[] banned) {
        Set<String> bannedSet = new HashSet<>();
        for (String word : banned) {
            bannedSet.add(word);
        }
        int maxFrequency = 0;
        Map<String, Integer> frequencies = new HashMap<>();
        StringBuilder sb = new StringBuilder();
        int length = paragraph.length();
        String mostCommon = "";
        // i = length 时让最后一个sb中的单词可以入map
        for (int i = 0; i <= length; i++) {
            // 空格时 isLetter 为 false
            if (i < length && Character.isLetter(paragraph.charAt(i))) {
                sb.append(Character.toLowerCase(paragraph.charAt(i)));
            } else if (sb.length() > 0) {
                String word = sb.toString();
                if (!bannedSet.contains(word)) {
                    int frequency = frequencies.getOrDefault(word, 0) + 1;
                    frequencies.put(word, frequency);
                    // 统计出现频率最大的单词
                    if (frequency > maxFrequency) {
                        maxFrequency = frequency;
                        mostCommon = word;
                    }
                }
                sb.setLength(0);
            }
        }
        return mostCommon;
    }

    public static void main(String[] args) {
        String paragraph = " Bob  hit a    a ball ,  ";
        String[] banned = new String[]{"hit"};

        String res = new Solution819_1().mostCommonWord(paragraph, banned);
        System.out.println(res);
    }

}
